package com.xinqing.test.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CommonFunctionUtil {
	private static Logger logger = LoggerFactory.getLogger(CommonFunctionUtil.class);

	/**
	 * get the date of today
	 *
	 * @param formatChar if formatChar is "-" ,get the return string is like 1990-01-10
	 *                   when formatChar is null ,it will be "-"
	 */
	public static String getCurrentDateString(String formatChar) {
		// init the formatChar
		if (formatChar == null)
			formatChar = "-";
		Calendar cal = Calendar.getInstance();
		int y = cal.get(Calendar.YEAR);
		int m = cal.get(Calendar.MONTH);
		int d = cal.get(Calendar.DATE);
		return y + formatChar + m + formatChar + d;
	}

	/**
	 * get the time of now
	 *
	 * @param formatChar if formatChar is ":" ,get the return string is like 1990-01-10
	 *                   when formatChar is null, it will be ":"
	 */
	public static String getCurrentTimeString(String formatChar) {
		// init the formatChar
		if (formatChar == null)
			formatChar = ":";
		Calendar cal = Calendar.getInstance();
		int h = cal.get(Calendar.HOUR_OF_DAY);
		int m = cal.get(Calendar.MINUTE);
		int s = cal.get(Calendar.SECOND);
		return h + formatChar + m + formatChar + s;
	}

	/**
	 * encrypt : md5
	 *
	 * @param inStr encrypt for s
	 * @return a string ,length is 32
	 */
//	public static String md5(String s) {
//		MessageDigest md;
//		StringBuffer buf = new StringBuffer("");
//		try {
//			md = MessageDigest.getInstance("MD5");
//			md.update(s.getBytes());
//			byte b[] = md.digest();
//			int i;
//			for (int offset = 0; offset < b.length; offset++) {
//				i = b[offset];
//				if (i < 0)
//					i += 256;
//				if (i < 16)
//					buf.append("0");
//				buf.append(Integer.toHexString(i));
//			}
//		} catch (NoSuchAlgorithmException e) {
//			e.printStackTrace();
//		}
//		return buf.toString();
//	}
	public static String md5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			logger.error("MessageDigest.getInstance exception:", e);
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuilder hexValue = new StringBuilder();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	public static Timestamp String2Timestamp(String s) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date = null;
		try {
			date = sdf.parse(s);
		} catch (ParseException e) {
			logger.error("String2Timestamp", e);
		}
		if (date != null)
			return new Timestamp(date.getTime());
		return null;
	}

	/**
	 * cut or change the date-time
	 *
	 * @param date
	 * @param format 1 : like 2012-12-12 09:08:49 ; 2 : like 2012-12-12 09:08 ; 3
	 *               :2012-12-12 ; 4 : 09:08:49 ;
	 * @return
	 */
	//
	public static String getFormatDate(String date, int format) {
		if (format == 1) {
			return date.substring(0, date.length() - 2);
		}
		if (format == 2) {
			String res = new String(getFormatDate(date, 1));
			return res.substring(0, res.length() - 2);
		}
		if (format == 3) {
			String[] res = date.split(" ");
			return new String(res[0]);
		}
		if (format == 4) {
			String[] res = date.split(" ");
			return new String(res[1]);
		}
		return "";
	}

	/**
	 * cut the string and add one string at last
	 *
	 * @param s         string s will be dealt
	 * @param length    new string length,if s.length()>length,it will be cut.
	 * @param addString replace string addString at last, when s.length>length
	 * @return
	 */
	public static String CutString(String s, int length, String addString) {
		if (s.length() > length) {
			String res = s.substring(0, length - 1);
			res = res + addString;
			return res;
		}
		return s;
	}

	public static String FormatRequestID(String idS) {
		String s = "";
		for (int i = 0; i < (6 - idS.length()); i++) {
			s += "0";
		}
		return s + idS;

	}

	public static String htmEncode(String target) {
		StringBuilder stringbuffer = new StringBuilder();
		int j = target.length();
		for (int i = 0; i < j; i++) {
			char c = target.charAt(i);
			switch (c) {
				case 60:
					stringbuffer.append("&lt;");
					break;
				case 62:
					stringbuffer.append("&gt;");
					break;
				case 38:
					stringbuffer.append("&amp;");
					break;
				case 34:
					stringbuffer.append("&quot;");
					break;
				case 169:
					stringbuffer.append("&copy;");
					break;
				case 174:
					stringbuffer.append("&reg;");
					break;
				case 165:
					stringbuffer.append("&yen;");
					break;
				case 8364:
					stringbuffer.append("&euro;");
					break;
				case 8482:
					stringbuffer.append("&#153;");
					break;
				case 13:
					if (i < j - 1 && target.charAt(i + 1) == 10) {
						stringbuffer.append("<br>");
						i++;
					}
					break;
				case 32:
					if (i < j - 1 && target.charAt(i + 1) == ' ') {
						stringbuffer.append(" &nbsp;");
						i++;
						break;
					}
				default:
					stringbuffer.append(c);
					break;
			}
		}
		return new String(stringbuffer.toString());
	}

	public static int[] changeColumnStringInfoToIntArray(String columnIds) {
		String[] cidstring = columnIds.split("%2C");
		int cids[] = new int[11];
		for (int i = 0; i < cids.length; i++) {
			cids[i] = 0;
		}
		cids[0] = cids[1] = 1;
		cids[cids.length - 1] = 1;
		for (int i = 0; i < cidstring.length; i++) {
			try {
				cids[Integer.valueOf(cidstring[i]) - 1] = 1;
			} catch (Exception e) {
				logger.info("Integer.valueOf exception： " + cidstring[i], e);
				continue;
			}
		}
		return cids;
	}

	public static String refineColumnIds(int[] cids) {
		String s = "";
		for (int i = 2; i < 9; i++) {
			if (cids[i] == 1) {
				s += ((i + 1) + ",");
			}
		}
		return s;
	}

	public static String getSlat(int length) {
		StringBuilder slatBuffer = new StringBuilder();
		String slatString = "1234567890qwertyuioplkjhgfdsazxcvbnmMNBVCXZASDFGHJKLPOIUYTREWQ";
		while (length-- != 0) {
			slatBuffer.append(slatString.charAt((Double.valueOf(Math.random() * 1000).intValue() % slatString.length())));
		}
		return slatBuffer.toString();
	}

	public static String getVcode(int length) {
		StringBuilder slatBuffer = new StringBuilder();
		String slatString = "1234567890";
		while (length-- != 0) {
			slatBuffer.append(slatString.charAt((Double.valueOf(Math.random() * 1000).intValue() % slatString.length())));
		}
		return slatBuffer.toString();
	}

	public static String getVcode(String mobile, int length) {
		String m = Long.toString(System.currentTimeMillis() - Long.parseLong(mobile));
		String vcode = m.substring(m.length() - length, m.length());
		return vcode;
	}

	/**
	 * @param size is pattern=[1-9]+[0-9]+(?)[1-9]+[0-9]+
	 * @param c    is splite char
	 * @return int[0] is width,int[1] is height;
	 */
	public static int[] sizeToValue(String size, char c) {
		int[] wh = {0, 0};
		wh[0] = Integer.valueOf(size.substring(0, size.indexOf(c)));
		wh[1] = Integer.valueOf(size.substring(1 + size.indexOf(c)));
		return wh;
	}


	public static String decrAuthkey(String authKey, String secretKey) {
		return DesSecret.decrypt(authKey, secretKey);
	}

	//11-18 5k,2k,1k,500,200,100,50,20
	public static BigDecimal getDistanceByZoom(int zoom) {
		switch (zoom) {
			case 11:
				return new BigDecimal(5000 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 12:
				return new BigDecimal(2000 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 13:
				return new BigDecimal(1000 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 14:
				return new BigDecimal(500 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 15:
				return new BigDecimal(200 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 16:
				return new BigDecimal(100 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 17:
				return new BigDecimal(50 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			case 18:
				return new BigDecimal(20 / zoom).setScale(3, BigDecimal.ROUND_HALF_UP);
			default:
				return null;
		}
	}

	public static String createAuthkey(String apt, String secretKey) {
		return DesSecret.encrypt(apt, secretKey);
	}
}
